package com.yege.lab.user;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

/**
 * user
 * @author yege
 */
@RestController
public class UserController {
    private final static Log log = LogFactory.getLog(UserController.class);
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public String register(HttpServletRequest request,@RequestBody UserDto user) {
        log.debug("register method was executed once");
        log.info("register method was executed once");
        log.warn("register method was executed once");
        log.error("register method was executed once");
        String activeCode = UUID.randomUUID().toString().replace("-", "");
        try {
            userService.registerUser(user.getEmail(),user.getName(),user.getPwd(),activeCode);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            log.warn(user.getEmail()+" register failure!");
            return e.getMessage();
        }
        log.info(user.getEmail()+" register successful!");
        return "success";
    }

    @GetMapping("/active")
    public String active(HttpServletRequest request,@RequestParam String code) {
        try {
            log.debug("active method was executed once");
            log.info("active method was executed once");
            log.warn("active method was executed once");
            log.error("active method was executed once");
            int r=userService.activeUser(code);
            if(r==1){
                log.info(code+":active successful!");
                return "success";
            }else {
                return "failure";
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return e.getMessage();
        }
    }

    @GetMapping("/user")
    public List<UserDto> queryUsers() {
        try {
            log.debug("queryUsers method was executed once");
            log.info("queryUsers method was executed once");
            log.warn("queryUsers method was executed once");
            log.error("queryUsers method was executed once");
            return userService.userList();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return null;
        }
    }

    @GetMapping("/version")
    public String version() {
        log.debug("version method was executed once");
        log.info("version method was executed once");
        log.warn("version method was executed once");
        log.error("version method was executed once");
        return "user server running version is V1.1";
    }
}